import React, { useEffect, useState } from "react";
import { RightOutlined, LeftOutlined } from "@ant-design/icons";
interface IndexProps {
  refs: React.RefObject<HTMLDivElement>;
}
const Index: React.FC<IndexProps> = ({ refs }) => {
  const [leftBottom, setLiftBottom] = useState(true);
  const [scrolls, setScrolls] = useState(true);

  const scrollLeft = () => {
    if (refs.current) {
      const scrollAmount = refs.current.offsetWidth;
      refs.current.scrollBy({
        left: -scrollAmount,
        behavior: "smooth",
      });
    }
  };
  const scrollRight = () => {
    if (refs.current) {
      const scrollAmount = refs.current.offsetWidth;
      refs.current.scrollBy({ left: scrollAmount, behavior: "smooth" });
    }
  };
  const clickBottom = () => {
    if (refs.current) {
      const isAtStart = refs.current.scrollLeft <= 20;
      setLiftBottom(!isAtStart);
    }
  };
  const cleckHot = () => {
    if (refs.current) {
      const { scrollLeft, scrollWidth, clientWidth } = refs.current;
      // Check if scrolled to the rightmost position
      const isAtEnd = scrollLeft + clientWidth >= scrollWidth - 40;
      setScrolls(!isAtEnd);
    }
  };
  useEffect(() => {
    const element = refs.current;
    element?.addEventListener("scroll", clickBottom);
    return () => {
      element?.removeEventListener("scroll", clickBottom);
    };
  }, []);
  useEffect(() => {
    const element = refs.current;
    element?.addEventListener("scroll", cleckHot);
    // Initial check in case container is already at the end
    clickBottom();
    return () => {
      element?.removeEventListener("scroll", cleckHot);
    };
  }, []);
  return (
    <div>
      {leftBottom && (
        <button
          style={{
            left: 40,
            position: "absolute",
            border: "none",
            top: "50%",
            boxShadow: "0px 0px 6px #aaa",
            marginLeft: 0,
            textAlign: "center",
            lineHeight: "30px",
            borderRadius: "50%",
            width: 30,
            height: 30,
            background: "#fff",
            transform: "translateY(-50%)",
          }}
          onClick={scrollLeft}
        >
          <LeftOutlined />
        </button>
      )}

      {scrolls && (
        <button
          style={{
            right: 10,
            border: "none",
            transform: "translateY(-50%)",
            position: "absolute",
            top: "50%",
            boxShadow: "0px 0px 6px #aaa",
            background: "#fff",
            textAlign: "center",
            lineHeight: "30px",
            borderRadius: "50%",
            width: 30,
            height: 30,
          }}
          onClick={scrollRight}
        >
          <RightOutlined />
        </button>
      )}
    </div>
  );
};

export default Index;
